/**
 * 认证服务
 * @module services/authService
 */

import api from './api';

/**
 * 管理员登录
 * @param {string} username - 用户名
 * @param {string} password - 密码
 * @returns {Promise<Object>} 登录结果
 */
export const login = async (username, password) => {
  try {
    const response = await api.post('/auth/login', { username, password });
    // 保存token到本地存储
    if (response.token) {
      localStorage.setItem('token', response.token);
      localStorage.setItem('user', JSON.stringify(response.user));
    }
    return response;
  } catch (error) {
    console.error('登录失败:', error);
    throw error;
  }
};

/**
 * 退出登录
 */
export const logout = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
};

/**
 * 获取当前用户信息
 * @returns {Promise<Object>} 用户信息
 */
export const getProfile = async () => {
  try {
    return await api.get('/auth/profile');
  } catch (error) {
    console.error('获取用户信息失败:', error);
    throw error;
  }
};

/**
 * 修改密码
 * @param {string} currentPassword - 当前密码
 * @param {string} newPassword - 新密码
 * @returns {Promise<Object>} 操作结果
 */
export const changePassword = async (currentPassword, newPassword) => {
  try {
    return await api.post('/auth/change-password', { currentPassword, newPassword });
  } catch (error) {
    console.error('修改密码失败:', error);
    throw error;
  }
};

/**
 * 检查是否已登录
 * @returns {boolean} 是否已登录
 */
export const isLoggedIn = () => {
  return !!localStorage.getItem('token');
};

/**
 * 获取当前用户
 * @returns {Object|null} 用户信息
 */
export const getCurrentUser = () => {
  const userStr = localStorage.getItem('user');
  return userStr ? JSON.parse(userStr) : null;
}; 